remove_next = (o) ->
    next = o._next
    if next
        remove_next next
        $(next).remove()
        o._next = undefined

select_html = (input, data, level) ->
    next = {}
    _ = $.html()
    if data.length
        _ """<select class="L#{level}"><option value="0"></option>"""
        for [value , name,  li] in data
            next[value] = li
            _ """<option value="#{value}">#{$.escape(name)}</option>"""
        _ '</select>'

    o = $(_.html())

    if data.length
        o.change ->
            
            self = $ @
            input.val @value
            remove_next @
            li = next[@value]
            if li
                n = select_html(input, li, level+1)
                this._next = n
                self.after n

    o[0]


select_val = (data , o , value, parent=[]) ->
    for [_value , name,  li] in data
        p = parent.slice()
        p.push _value

        if `_value == value`
            for v  in p
                o.value = v
                $(o).trigger('change')
                o=o._next

            break
        else if li.length
            select_val(li, o, value, p)

$.chain_select = (name, data, value=0) ->
    input = $ """<input type="hidden" name="#{name}" value="0">"""
    o = select_html(input, data, 1)
    span = $ '<span/>'
    span.append o
    span.append input
    select_val data, o, value
    return span
